package edu.nf.ch06.config;

import edu.nf.ch06.filter.MyFilter;
import edu.nf.ch06.filter.TestFilter;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;

/**
 * @author ZJL
 * @date 2025/9/12
 */
@Configuration
/**
 * @ServletComponentScan注解
 * 是springboot提供的专门用于扫描servlet组件(servlet、Filter、Listener)
 * 注意：这种扫描有一个缺点，当有多个过滤器形成过滤链的时候，无法按照指定顺序来执行
 */
//@ServletComponentScan("edu.nf.ch06.filter")
public class MvcConfig {
    /**
     * 第二种方式使用springboot提供的动态注册器(RegistrationBean)
     * 来注册Servlet组件，好处是可以控制过滤链的执行顺序
     * 有三种动态注册器分别是Servlet、Filter、Listener
     * ServletRegistrationBean
     * FilterRegistrationBean
     * ServletListenerRegistrationBean
     */
    @Bean
    public FilterRegistrationBean TestFilter(){
        FilterRegistrationBean  registrationBean = new FilterRegistrationBean();
        // 装配过滤器
        registrationBean.setFilter(new TestFilter());
        registrationBean.setName("testFilter");
        registrationBean.addUrlPatterns("/*");
        // 设置优先级别,数值越小优先级越高
        registrationBean.setOrder(1);
        return registrationBean;
    }

    @Bean
    public FilterRegistrationBean MyFilter(){
        FilterRegistrationBean  registrationBean = new FilterRegistrationBean();
        // 装配过滤器
        registrationBean.setFilter(new MyFilter());
        registrationBean.setName("myFilter");
        registrationBean.addUrlPatterns("/*");
        // 设置优先级别,数值越小优先级越高
        registrationBean.setOrder(2);
        return registrationBean;
    }
}
